package day15.atm;

import day9.atm.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 转账界面
 */
public class TransferPanel extends JPanel implements ActionListener {
    private ATMFrame atmFrame;
    private ImageIcon saveImg = new ImageIcon("images/buttonSure.jpg");
    private Font font = new Font("黑体",Font.BOLD,30);
    private JLabel saveLabel = new JLabel("转账金额：");
    private JLabel saveLabel1 = new JLabel("账号：");
    private JTextField accountField = new JTextField();
    private JTextField accountField1 = new JTextField();
    private JButton saveButton = new JButton(saveImg);

    public TransferPanel(ATMFrame atmFrame){
        this.atmFrame = atmFrame;
        this.setLayout(null);
        saveLabel.setBounds(300,200,230,50);
        saveLabel.setFont(font);
        accountField.setBounds(500,200,230,50);
        accountField.setFont(font);

        saveLabel1.setBounds(300,250,230,50);
        saveLabel1.setFont(font);
        accountField1.setBounds(500,250,230,50);
        accountField1.setFont(font);

        saveButton.setBounds(442,310,140,50);
        saveButton.addActionListener(this);
        this.add(saveLabel);
        this.add(saveLabel1);
        this.add(accountField);
        this.add(accountField1);
        this.add(saveButton);
        this.setOpaque(false);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == saveButton){
            SuperArray users = atmFrame.getUsers();
            User loginUser= atmFrame.getLoginUser();
            if (Double.parseDouble(accountField.getText()) > loginUser.getBalance()){
                JOptionPane.showMessageDialog(this,"你的余额不足！");
                return;
            }
            if (accountField1.getText().equals(loginUser.getAccount())){
                JOptionPane.showMessageDialog(this,"不能转给自己");
                return;
            }
            for (int i = 0;i < users.size();i++){
                User otherUser = (User) users.get(i);
                if (otherUser.getAccount().equals(accountField1.getText())){
                    loginUser.setBalance(loginUser.getBalance() - Double.parseDouble(accountField.getText()));
                    otherUser.setBalance(otherUser.getBalance() + Double.parseDouble(accountField.getText()));
                    JOptionPane.showMessageDialog(this,"转账成功");
                    atmFrame.switchPanel("menu");
                    return;
                }
            }

            JOptionPane.showMessageDialog(this,"输入的账号不正确");
        }
    }
}
